import Vue from 'vue'
import VueRouter from 'vue-router'
import reg from '@/views/Reg/Reg.vue'
import login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/article/ArtCate.vue'
import ArtList from '@/views/Menus/article/ArtList.vue'
import store from '@/store'
import ElementUI from 'element-ui'

Vue.use(VueRouter)

const routes = [{ path: '/reg', component: reg },
  { path: '/login', component: login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [{
      path: 'home',
      component: home
    }, {
      path: 'user-info',
      component: UserInfo
    }, {
      path: 'user-avatar',
      component: UserAvatar
    }, {
      path: 'user-pwd',
      component: UserPwd
    }, {
      path: 'art-cate',
      component: ArtCate
    }, {
      path: 'art-list',
      component: ArtList
    }]
  }
]

const router = new VueRouter({
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, from, next) => {
  if (to.path === '/' && !store.state.user.token) {
    ElementUI.Message({
      showClose: true,
      message: '您还没有登录请登录',
      type: 'error'
    })
    next('/login')
  } else {
    next()
  }
})
export default router
